# coding: utf-8
from flask import Flask, render_template, redirect, url_for, request
from flask_wtf.csrf import CsrfProtect
from forms import TableForm
from dao import Dao
from datetime import datetime

csrf = CsrfProtect()
app = Flask(__name__)
app.config["SECRET_KEY"] = "123"
csrf.init_app(app)
dao = Dao()

@app.route("/index", methods=["GET", "POST"])
def index():
    args = request.args
    page = args.get("page", 1)
    q = args.get("q", "")

    records = dao.getRecords(page=page, q=q)

    return render_template("index.html", records=records, q=q, page=page)


@app.route("/add", methods=["GET", "POST"])
def add():
    form = TableForm()
    ## 增加数据
    if form.validate_on_submit():
        record = {
            "channel_name" : form.channel_name.data,
            "channel_date" : form.channel_date.data,
            "channel_address" : form.channel_address.data,
            "channel_contributor" : form.channel_contributor.data,
            "company" : form.company.data,
            "company_description":form.company_description.data,
            "company_tags" : form.company_tags.data,
            "person" : form.person.data,
            "person_description" : form.person_description.data,
            "person_title" : form.person_title.data,
            "person_phone" : form.phone.data,
            "email" : form.email.data,
            "is_stored": False,
            "touched_date" : "",
            "is_touched" : False,
            "demand" : "",
            "create_time": datetime.now(),
            "update_time": datetime.now()
        }
        dao.add(record)
        return redirect(url_for("index"))

    return render_template("add.html", form=form)


@app.route("/edit/<item_id>", methods=["GET", "POST"])
def edit(item_id):
    form = TableForm()
    ## 修改数据
    record = dao.getRecord(id=item_id)
    if form.validate_on_submit():
        update = {
            "is_touched": True,
            "touched_date": form.touched_date.data,
            "touched_person": form.touched_person.data,
            "demand": form.demand.data,
            'update_time': datetime.now()
        }
        dao.update(item_id, update)
        return redirect(url_for("index"))

    return render_template("edit.html", record=record, form=form)


@app.route("/delete/<item_id>", methods=["GET"])
def delete(item_id):
    if item_id:
        dao.delete(item_id)
    
    return redirect(url_for("index"))


@app.route("/", methods=["GET", "POST"])
def origin():
    return redirect(url_for("index"))



if __name__ == "__main__":
    app.run(debug=True, host="0.0.0.0", port=9011)